package com.gouaixin.bee.beeframework2.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.activity.B6_ziliaoActivity;
import com.gouaixin.bee.beeframework2.adapter.TuijianAdapter;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.XHttpUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2015/3/4.
 */
public class I0_tuijianFargment extends Fragment {

    View mainView;



    ListView list;
    TuijianAdapter mAdapter;
    JSONArray jsonArray=new JSONArray();//推荐对象的json数组

    String HerId="";//传出对象的id
    String Herjuli="";//传出对象的距离
    String Herhight="";//传出对象的身高
    String HerGender ="2";//传出对象的性别

    /**
     *  在这里实现Fragment数据的缓加载.    
     */
    public boolean isVisible;

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    public  void onVisible() {


    }


    public void onInvisible() {
    }


    //是否是从详情界面返回
    boolean isDetailBack=false;
    @Override
    public void onResume() {
        super.onResume();
        isDetailBack= PreferencesUtils.getBoolean(getActivity(),"isDetailBack",false);
        mLog.e("isDetailBack=" + isDetailBack);

//        if(isDetailBack){
            //从详情界面返回时，刷新打招呼和关注的按钮
            mLog.e("从详情界面返回时，刷新打招呼和关注的按钮");
            refreshButton();
            //重置
            isDetailBack=false;
            PreferencesUtils.putBoolean(getActivity(),"isDetailBack",false);
//        }

    }

    private void refreshButton() {
        mLog.e("执行：mAdapter.notifyDataSetChanged();");
//        initContent();
        mAdapter.notifyDataSetChanged();



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         mainView = inflater.inflate(R.layout.i0_tuijian, null);
        String mGender=PreferencesUtils.getString(getActivity(),"gender","男");

        mLog.e("mGender=" + mGender);

        if(mGender.equals("男")){
            HerGender ="2";//获取女生
        }else {
            HerGender ="1";//获取男生
        }

        initPullToRefresh();

        initContent();

        getTuijian();



        return mainView;
    }



    private void initContent() {


        list= (ListView) mainView.findViewById(R.id.list);

         mAdapter=new TuijianAdapter(getActivity());

        list.setAdapter(mAdapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                try {
                    mLog.e("进入资料界面");
                    Intent it = new Intent().setClass(getActivity(), B6_ziliaoActivity.class);
                    JSONObject jsonOb = (JSONObject) jsonArray.opt(position);
                    HerId=jsonOb.getString("id");
                    Herjuli=jsonOb.getString("juli");
                    Herhight=jsonOb.getString("height");
                    Log.e("test","外面的fragment传递的数据：id="+HerId+"\tjuli="+Herjuli+"\theight="+Herhight);

                    it.putExtra("HerId",HerId);
                    it.putExtra("Herjuli",Herjuli);
                    it.putExtra("Herhight",Herhight);
                    startActivity(it);
                } catch (JSONException e) {
                    AbToastUtil.showToast(getActivity(),"网络故障，请稍后再试");
                    e.printStackTrace();
                }

            }
        });


    }


    /**下拉刷新：START**/
    /**下拉刷新：START**/

    private AbPullToRefreshView mAbPullToRefreshView = null;

    private void initPullToRefresh() {

        mAbPullToRefreshView= (AbPullToRefreshView) mainView.findViewById(R.id.root);

        // 设置监听器
        mAbPullToRefreshView.setOnHeaderRefreshListener(new AbPullToRefreshView.OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(AbPullToRefreshView abPullToRefreshView) {
                refreshTask();

            }
        });
        mAbPullToRefreshView.setOnFooterLoadListener(new AbPullToRefreshView.OnFooterLoadListener() {
            @Override
            public void onFooterLoad(AbPullToRefreshView abPullToRefreshView) {
                loadMoreTask();
            }
        });

        // 设置进度条的样式
        mAbPullToRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
        mAbPullToRefreshView.getFooterView().setFooterProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));

    }


    public void refreshTask(){
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                AbDialogUtil.removeDialog(getActivity());
//                Toast.makeText(getActivity(),"执行刷新方法:"+"+"+new Random().nextInt(100),Toast.LENGTH_SHORT).show();
                getTuijian();

                mAbPullToRefreshView.onHeaderRefreshFinish();
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            };
        });

        mAbTask.execute(item);
    }

    public void loadMoreTask(){
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                AbDialogUtil.removeDialog(getActivity());
//                Toast.makeText(getActivity(),"执行加载更多方法:"+"+"+new Random().nextInt(100),Toast.LENGTH_SHORT).show();
                getTuijianMore();
                mAbPullToRefreshView.onFooterLoadFinish();
            }
            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            };
        });

        mAbTask.execute(item);
    }

    /**下拉刷新：END**/

    /***
     * 得到推荐用户对象
     * @return
     */
    public  String getTuijian() {
        String url="http://jiekou.hydgyx.com/api/interface_friends.php";
        final String[] result = {""};

        RequestParams params = new RequestParams();
        params.addBodyParameter("tuijian", "1");//1.推荐，0.最新
        params.addBodyParameter("Gender", HerGender);//1.男，2.女

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        mLog.e(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("得到推荐用户对象：请求成功：" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        result[0] =XHttpUtils.Unicode2Chinese(responseInfo.result);

                        try {
                            jsonArray=new JSONArray(result[0]);
                            mAdapter.setJson(jsonArray);
                            mAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {
                        mLog.e("开始请求：");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );
        return result[0];
    }

    /***
     * 得到更多推荐用户对象
     * @return
     */
    int temp=0;
    public  String getTuijianMore() {
        String url="http://jiekou.hydgyx.com/api/interface_friends.php";
        final String[] result = {""};

        RequestParams params = new RequestParams();
        params.addBodyParameter("tuijian", "1");//1.推荐，0.最新
        params.addBodyParameter("Gender", HerGender);//1.男，2.女
        temp++;
        params.addBodyParameter("p", temp+"");//1.男，2.女

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        mLog.e(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("得到更多推荐用户对象：请求成功：" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        result[0] =XHttpUtils.Unicode2Chinese(responseInfo.result);

                        try {
                            JSONArray jsonArray2=new JSONArray(result[0]);
                            jsonArray=hebingjsonArray(jsonArray,jsonArray2);
                            mAdapter.setJson(jsonArray);
                            mAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {
                        mLog.e("开始请求：");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );
        return result[0];
    }


    /****
     * 合并两个jsonarray
     * @param jsonArray
     * @param jsonArray2
     * @return
     */
    private JSONArray hebingjsonArray(JSONArray jsonArray, JSONArray jsonArray2) {
        JSONArray jsonArray3=new JSONArray();
        for (int i = 0; i < jsonArray.length(); i++) {
            jsonArray3.put(jsonArray.opt(i));
        }
        for (int i = 0; i < jsonArray2.length(); i++) {
            jsonArray3.put(jsonArray2.opt(i));
        }

        return jsonArray3;
    }

    /***
     * Java中将两个jsonarray合并为一个字符串输出
     * @param mData
     * @param array
     * @return
     */
    public static String joinJSONArray(JSONArray mData, JSONArray array) {
        StringBuffer buffer = new StringBuffer();
        try {
            int len = mData.length();
            for (int i = 0; i < len; i++) {
                JSONObject obj1 = (JSONObject) mData.get(i);
                if (i == len - 1)
                    buffer.append(obj1.toString());
                else
                    buffer.append(obj1.toString()).append(",");
            }
            len = array.length();
            if (len > 0)
                buffer.append(",");
            for (int i = 0; i < len; i++) {
                JSONObject obj1 = (JSONObject) array.get(i);
                if (i == len - 1)
                    buffer.append(obj1.toString());
                else
                    buffer.append(obj1.toString()).append(",");
            }
//          buffer.insert(0, "[").append("]");
            return buffer.toString();
        } catch (Exception e) {
        }
        return null;
    }


}
